package com.aishua.fire.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Random;





/**
 * md5工具类
 * @author Administrator
 *
 */
public class MD5Util {
	
	private MD5Util() {
	    throw new IllegalStateException("MD5Util class");
	}
	
	 private static final String DIGEST_ALGORITHM = "MD5";
	    private static final char HEX_DIGITS[] = 
	        {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	        
	    public static final String md5(String msg) {
	        if (msg == null) {
	            return null;
	        }
	        MessageDigest md5 = null;
	        try {
	            md5 = MessageDigest.getInstance(DIGEST_ALGORITHM);
	        } catch (NoSuchAlgorithmException e) {
	            e.printStackTrace();
	        }
	        if (md5 == null) {
	            return null;
	        }
	        try {
	            md5.update(msg.getBytes("utf-8"));
	        }catch(Exception ex){}
	        byte[] digest = md5.digest();
	        return byte2Hex(digest);
	        
	    }
	        
	    public static String getNonceStr(int length){
	        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	        Random random = new Random();
	        StringBuffer sb = new StringBuffer();
	        for (int i = 0; i < length; i++) {
	            int number = random.nextInt(base.length());
	            sb.append(base.charAt(number));
	        }
	        return sb.toString();
	    }
	        
	    private static final String byte2Hex(byte[] b) {
	        int j = b.length;
	        char str[] = new char[j * 2];
	        int k = 0;
	        for (int i = 0; i < j; i++) {
	            byte byte0 = b[i];
	            str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf];
	            str[k++] = HEX_DIGITS[byte0 & 0xf];
	        }
	        return new String(str);
	    }
	    


	    //其次，这是我的加密函数 。传入排序后map，生成签名
	    public String getSign(Map<String, Object> signMap){
	        //组装md5签名字符串
	        String sign="";
	        for(String nameKey:signMap.keySet()){
	            sign += nameKey+"="+signMap.get(nameKey)+"&";
	        }
	        sign+="key="+"wuhanwuhanbeijing123456712345678";
	        //调用md5签名方法
	        return MD5Util.md5(sign).toUpperCase();
	    }
	    
	    public static void main(String[] args) {
			System.out.println(md5("admin"));
		}
	    
}
